{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "相等间隔"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "生成的分级间断点（左闭右开区间）：\n",
      "[-6.39828590e+09 -4.79871442e+09 -3.19914295e+09 -1.59957147e+09\n",
      "  0.00000000e+00  3.72546917e+09  7.45093834e+09  1.11764075e+10\n",
      "  1.49018767e+10]\n",
      "\n",
      "验证区间分布：\n",
      "Level 1: [-6398285895.97, -4798714421.98)\n",
      "Level 2: [-4798714421.98, -3199142947.98)\n",
      "Level 3: [-3199142947.98, -1599571473.99)\n",
      "Level 4: [-1599571473.99, 0.00)\n",
      "Level 5: [0.00, 3725469168.07)\n",
      "Level 6: [3725469168.07, 7450938336.15)\n",
      "Level 7: [7450938336.15, 11176407504.22)\n",
      "Level 8: [11176407504.22, 14901876672.29)\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# 读取所有csv文件\n",
    "files = [\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2020_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2015_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2010_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2005_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2001_2.csv\"\n",
    "]\n",
    "\n",
    "all_coefficients = []\n",
    "\n",
    "if not files:\n",
    "    raise FileNotFoundError(\"未找到CSV文件，请检查路径设置\")\n",
    "\n",
    "for filepath in files:\n",
    "    df = pd.read_csv(filepath,encoding='GB2312')\n",
    "    coeff_cols = [col for col in df.columns if col.endswith('_coefficient')]\n",
    "    \n",
    "    if not coeff_cols:\n",
    "        print(f\"文件 {filepath} 中未找到以'_coefficient'结尾的列\")\n",
    "        continue\n",
    "    \n",
    "    for col in coeff_cols:\n",
    "        data = df[col].dropna()\n",
    "        all_coefficients.extend(data.tolist())\n",
    "\n",
    "if not all_coefficients:\n",
    "    raise ValueError(\"所有文件中均未找到有效的'_coefficient'列数据\")\n",
    "\n",
    "# 转换为numpy数组并分离正负数\n",
    "coefficients = np.array(all_coefficients)\n",
    "negative = coefficients[coefficients < 0]\n",
    "positive = coefficients[coefficients > 0]\n",
    "\n",
    "if len(negative) == 0:\n",
    "    raise ValueError(\"数据中没有负数值，无法生成负向分级\")\n",
    "if len(positive) == 0:\n",
    "    raise ValueError(\"数据中没有正数值，无法生成正向分级\")\n",
    "\n",
    "# 计算分界点\n",
    "min_neg = np.min(negative)\n",
    "max_pos = np.max(positive)\n",
    "\n",
    "# 生成分界点（左闭右开区间）\n",
    "neg_breaks = np.linspace(min_neg, 0, num=5)\n",
    "pos_breaks = np.linspace(0, max_pos, num=5)\n",
    "\n",
    "# 合并并去重0值\n",
    "breaks = list(neg_breaks) + list(pos_breaks[1:])\n",
    "\n",
    "print(\"生成的分级间断点（左闭右开区间）：\")\n",
    "print(np.round(breaks, 4))\n",
    "\n",
    "# 验证区间有效性\n",
    "print(\"\\n验证区间分布：\")\n",
    "for i in range(len(breaks)-1):\n",
    "    print(f\"Level {i+1}: [{breaks[i]:.2f}, {breaks[i+1]:.2f})\")\n",
    "\n",
    "# 保存结果示例\n",
    "output = pd.DataFrame({\n",
    "    \"分级区间\": [f\"[{breaks[i]:.2f}, {breaks[i+1]:.2f})\" for i in range(len(breaks)-1)],\n",
    "    \"级别类型\": [\"负向\" if i < 4 else \"正向\" for i in range(8)]\n",
    "})\n",
    "output.to_csv(r\"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\classification_breaks.csv\", encoding='GB2312',index=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自然间断法分级"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "生成的自然间断点分级（左闭右开区间）：\n",
      "[-6.39828590e+09 -4.13293356e+09 -2.12887245e+09 -7.62559928e+08\n",
      "  0.00000000e+00  7.61757783e+08  2.74130621e+09  6.88919283e+09\n",
      "  1.49018767e+10]\n",
      "\n",
      "验证区间分布：\n",
      "Level 1: [-6398285895.97, -4132933563.53) 负向\n",
      "Level 2: [-4132933563.53, -2128872448.03) 负向\n",
      "Level 3: [-2128872448.03, -762559927.90) 负向\n",
      "Level 4: [-762559927.90, 0.00) 负向\n",
      "Level 5: [0.00, 761757782.90) 正向\n",
      "Level 6: [761757782.90, 2741306212.87) 正向\n",
      "Level 7: [2741306212.87, 6889192826.68) 正向\n",
      "Level 8: [6889192826.68, 14901876672.29) 正向\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import jenkspy\n",
    "\n",
    "files = [\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2020_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2015_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2010_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2005_2.csv\",\n",
    "    \"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\输出数据\\csv\\MGWR结果\\MGWR_2001_2.csv\"\n",
    "]\n",
    "\n",
    "all_coefficients = []\n",
    "\n",
    "for filepath in files:\n",
    "    df = pd.read_csv(filepath,encoding='GB2312')\n",
    "    coeff_cols = [col for col in df.columns if (col.endswith('_coefficient')\n",
    "                  and '截距' not in col)]\n",
    "    \n",
    "    if not coeff_cols:\n",
    "        print(f\"文件 {filepath} 中未找到以'_coefficient'结尾的列\")\n",
    "        continue\n",
    "    \n",
    "    for col in coeff_cols:\n",
    "        data = df[col].dropna()\n",
    "        all_coefficients.extend(data.tolist())\n",
    "\n",
    "if not all_coefficients:\n",
    "    raise ValueError(\"所有文件中均未找到有效的'_coefficient'列数据\")\n",
    "\n",
    "# 转换为numpy数组并分离正负数\n",
    "coefficients = np.array(all_coefficients)\n",
    "negative = coefficients[coefficients < 0]\n",
    "positive = coefficients[coefficients > 0]\n",
    "\n",
    "# 校验数据量\n",
    "if len(negative) < 4:\n",
    "    raise ValueError(\"负数数据量不足（需要至少4个值），无法生成4级自然间断点\")\n",
    "if len(positive) < 4:\n",
    "    raise ValueError(\"正数数据量不足（需要至少4个值），无法生成4级自然间断点\")\n",
    "\n",
    "# 计算自然间断点\n",
    "def calc_jenks_breaks(data, n_classes, boundary):\n",
    "    # 使用jenkspy库的jenks_breaks函数计算数据的自然断点\n",
    "    breaks = jenkspy.jenks_breaks(data, n_classes=n_classes)\n",
    "    breaks[-1 if boundary==\"max\" else 0] = 0.0  # 替换边界值为0\n",
    "    return np.sort(breaks)  # 确保升序排列\n",
    "\n",
    "# 处理负数区间（替换最大值边界为0）\n",
    "neg_breaks = calc_jenks_breaks(negative, n_classes=4, boundary=\"max\")\n",
    "\n",
    "# 处理正数区间（替换最小值边界为0）\n",
    "pos_breaks = calc_jenks_breaks(positive, n_classes=4, boundary=\"min\")\n",
    "\n",
    "# 合并并去重\n",
    "full_breaks = np.concatenate([neg_breaks, pos_breaks])\n",
    "unique_breaks = np.unique(full_breaks)  # 自动排序并去重\n",
    "\n",
    "# 验证区间连续性\n",
    "if not np.all(np.diff(unique_breaks) > 0):\n",
    "    raise ValueError(\"分界点存在重叠或无序现象\")\n",
    "\n",
    "print(\"生成的自然间断点分级（左闭右开区间）：\")\n",
    "print(np.round(unique_breaks, 4))\n",
    "\n",
    "# 生成区间说明\n",
    "print(\"\\n验证区间分布：\")\n",
    "for i in range(len(unique_breaks)-1):\n",
    "    lower = unique_breaks[i]\n",
    "    upper = unique_breaks[i+1]\n",
    "    direction = \"负向\" if upper <= 0 else \"正向\"\n",
    "    print(f\"Level {i+1}: [{lower:.2f}, {upper:.2f}) {direction}\")\n",
    "\n",
    "# # 保存结果\n",
    "# output = pd.DataFrame({\n",
    "#     \"分级区间\": [f\"[{unique_breaks[i]:.2f}, {unique_breaks[i+1]:.2f})\" \n",
    "#                for i in range(len(unique_breaks)-1)],\n",
    "#     \"级别类型\": [\"负向\" if b < 0 else \"正向\" for b in unique_breaks[:-1]]\n",
    "# })\n",
    "# output.to_csv(\"natural_breaks_classification.csv\", index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "myenv2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
